package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.SysRuleSet;
import com.ysd.lis.mapper.SysRuleSetMapper;
import com.ysd.lis.request.RuleSetListParam;
import com.ysd.lis.service.SysRuleSetService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 规则设置 服务实现类
 * </p>
 *
 * @author LiuQi
 * @since 2024-01-31
 */
@Service
public class SysRuleSetServiceImpl extends ServiceImpl<SysRuleSetMapper, SysRuleSet> implements SysRuleSetService {

    @Autowired
    SysRuleSetMapper sysRuleSetMapper;

    @Autowired
    SysRuleSetService sysRuleSetService;

    @Override
    public Result getRuleSetList(RuleSetListParam ruleSetListParam) {
        LambdaQueryWrapper<SysRuleSet> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRuleSet::getDelFlag, 0).eq(StrUtil.isNotEmpty(ruleSetListParam.getModuleName()), SysRuleSet::getModuleName, ruleSetListParam.getModuleName()).eq(StrUtil.isNotEmpty(ruleSetListParam.getOrgId()), SysRuleSet::getOrgId, ruleSetListParam.getOrgId()).and(StrUtil.isNotEmpty(ruleSetListParam.getKeyWords()), wrapper -> wrapper.like(SysRuleSet::getRuleCode, ruleSetListParam.getKeyWords()).or().like(SysRuleSet::getRuleName, ruleSetListParam.getKeyWords())).orderByDesc(SysRuleSet::getCreateTime);
        List<SysRuleSet> sysRuleSets = sysRuleSetMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", sysRuleSets);
    }

    @Override
    public Result addRuleSet(SysRuleSet sysRuleSet) {
//        SysUser sysUser = RedisUserManager.getUser();
//        sysRuleSet.setOrgId(sysUser.getOrgId());
        boolean save = this.save(sysRuleSet);
        if (save) {
            return Result.succ(1, "添加成功！", save);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result updateRuleSet(SysRuleSet sysRuleSet) {
//        SysUser sysUser = RedisUserManager.getUser();
//        sysRuleSet.setOrgId(sysUser.getOrgId());
        boolean save = this.updateById(sysRuleSet);
        if (save) {
            return Result.succ(1, "编辑成功！", save);
        } else {
            return Result.fail("编辑失败！");
        }
    }

    @Override
    public Result removeRuleSet(SysRuleSet sysRuleSet) {
        boolean remove = this.removeById(sysRuleSet.getId());
        if (remove) {
            return Result.succ(1, "删除成功！", remove);
        } else {
            return Result.fail("删除失败！");
        }
    }

    /**
     * @param ruleCode
     * @param quantity
     * @return
     */
    public List<String> createRuleCodeList(String ruleCode, int quantity) {
        List<String> resultList = new ArrayList<>();
        if (StrUtil.isNotEmpty(ruleCode) && quantity >= 1) {
            LambdaQueryWrapper<SysRuleSet> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysRuleSet::getDelFlag, 0).eq(SysRuleSet::getRuleCode, ruleCode);
            List<SysRuleSet> sysRuleSets = sysRuleSetMapper.selectList(lambdaQueryWrapper);

            SysRuleSet sysRuleSet = sysRuleSets.isEmpty() ? null : sysRuleSets.get(0);

            if (BeanUtil.isEmpty(sysRuleSet)) {
                throw new RuntimeException("请先配置条码生成规则");
            }

            StringBuilder proFix = new StringBuilder();
            // 拼接前缀
            proFix.append(StrUtil.isEmpty(sysRuleSet.getPreFix()) ? "" : StrUtil.trim(sysRuleSet.getPreFix()));
            // 拼接日期格式
            proFix.append(StrUtil.isEmpty(sysRuleSet.getDatetimeFormat()) ? "" : DateUtil.format(new Date(), sysRuleSet.getDatetimeFormat()));
            // 拼接后缀
            proFix.append(StrUtil.isEmpty(sysRuleSet.getPostFix()) ? "" : StrUtil.trim(sysRuleSet.getPostFix()));
            String restDatetimeValue = StrUtil.isEmpty(sysRuleSet.getRestDateFmt()) ? "" : DateUtil.format(new Date(), sysRuleSet.getRestDateFmt());
            int startId = sysRuleSet.getCurrentId();
            if ((!restDatetimeValue.equals(sysRuleSet.getRestDateValue())) && StrUtil.isNotEmpty(restDatetimeValue)) {
                // 设置重置日期值
                sysRuleSet.setRestDateValue(restDatetimeValue);
                startId = sysRuleSet.getStartId();
            }
            // 设置当前值
            sysRuleSet.setCurrentId((startId + quantity));
            int i1 = sysRuleSetMapper.updateById(sysRuleSet);
            String string = proFix.toString();
            for (int i = startId; i < sysRuleSet.getCurrentId().intValue(); i++) {
                String s = sysRuleSet.getIdLength().intValue() == 0 ? string + i : string + StringUtils.leftPad(i + "", sysRuleSet.getIdLength().intValue(), "0");
                resultList.add(s);
            }
        }
        return resultList;
    }

    @Override
    public List<String> createRuleCodeListByDate(String ruleCode, int quantity, Timestamp sampleDa) {
        List<String> resultList = new ArrayList<>();
        if (StrUtil.isNotEmpty(ruleCode) && quantity >= 1) {
            LambdaQueryWrapper<SysRuleSet> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysRuleSet::getDelFlag, 0).eq(SysRuleSet::getRuleCode, ruleCode);
            List<SysRuleSet> sysRuleSets = sysRuleSetMapper.selectList(lambdaQueryWrapper);

            SysRuleSet sysRuleSet = sysRuleSets.isEmpty() ? null : sysRuleSets.get(0);

            if (BeanUtil.isEmpty(sysRuleSet)) {
                throw new RuntimeException("请先配置条码生成规则");
            }

            StringBuilder proFix = new StringBuilder();
            // 拼接前缀
            proFix.append(StrUtil.isEmpty(sysRuleSet.getPreFix()) ? "" : StrUtil.trim(sysRuleSet.getPreFix()));
            // 拼接日期格式
            proFix.append(StrUtil.isEmpty(sysRuleSet.getDatetimeFormat()) ? "" : DateUtil.format(sampleDa, sysRuleSet.getDatetimeFormat()));
            // 拼接后缀
            proFix.append(StrUtil.isEmpty(sysRuleSet.getPostFix()) ? "" : StrUtil.trim(sysRuleSet.getPostFix()));
            String restDatetimeValue = StrUtil.isEmpty(sysRuleSet.getRestDateFmt()) ? "" : DateUtil.format(sampleDa, sysRuleSet.getRestDateFmt());
            int startId = sysRuleSet.getCurrentId();
            if ((!restDatetimeValue.equals(sysRuleSet.getRestDateValue())) && StrUtil.isNotEmpty(restDatetimeValue)) {
                // 设置重置日期值
                sysRuleSet.setRestDateValue(restDatetimeValue);
                startId = sysRuleSet.getStartId();
            }
            // 设置当前值
            sysRuleSet.setCurrentId((startId + quantity));
            int i1 = sysRuleSetMapper.updateById(sysRuleSet);
            String string = proFix.toString();
            for (int i = startId; i < sysRuleSet.getCurrentId().intValue(); i++) {
                String s = sysRuleSet.getIdLength().intValue() == 0 ? string + i : string + StringUtils.leftPad(i + "", sysRuleSet.getIdLength().intValue(), "0");
                resultList.add(s);
            }
        }
        return resultList;
    }

    /**
     * @param ruleCode
     * @param quantity
     * @return
     */
    public String createRuleCodeListBySampleDa(String ruleCode, int quantity,String sampleDa,int count) {
        String string ="";
        List<String> resultList = new ArrayList<>();
        if (StrUtil.isNotEmpty(ruleCode) && quantity >= 1) {
            LambdaQueryWrapper<SysRuleSet> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysRuleSet::getDelFlag, 0).eq(SysRuleSet::getRuleCode, ruleCode);
            List<SysRuleSet> sysRuleSets = sysRuleSetMapper.selectList(lambdaQueryWrapper);

            SysRuleSet sysRuleSet = sysRuleSets.isEmpty() ? null : sysRuleSets.get(0);

            if (BeanUtil.isEmpty(sysRuleSet)) {
                throw new RuntimeException("请先配置条码生成规则");
            }

            StringBuilder proFix = new StringBuilder();

            int startId = sysRuleSet.getCurrentId()+count;
            // 拼接前缀
            proFix.append(StrUtil.isEmpty(sysRuleSet.getPreFix()) ? "" : StrUtil.trim(sysRuleSet.getPreFix()));
            // 拼接日期格式
            proFix.append(StrUtil.isEmpty(sysRuleSet.getDatetimeFormat()) ? "" : DateUtil.format(DateUtil.parse(sampleDa,"yyyy-MM-dd HH:mm:ss"), sysRuleSet.getDatetimeFormat()));
            // 拼接后缀
            proFix.append(StrUtil.isEmpty(sysRuleSet.getPostFix()) ? "" : StrUtil.trim(sysRuleSet.getPostFix()));

            string = proFix.toString()+startId;
        }
        return string;
    }

    @Override
    public Result copyRuleByOrgId(OrganizationDTO organizationDTO) {
        try {
            String letter = AlphabetArray.Alphabet[organizationDTO.getOrgIndex()];
            sysRuleSetMapper.delete(new LambdaQueryWrapper<SysRuleSet>().eq(SysRuleSet::getOrgId, organizationDTO.getGoalOrgId()));
            List<SysRuleSet> sysRuleSets = sysRuleSetMapper.selectList(new LambdaQueryWrapper<SysRuleSet>().eq(SysRuleSet::getDelFlag, 0).eq(SysRuleSet::getOrgId, organizationDTO.getSourceOrgId()));
            for (SysRuleSet sysRuleSet : sysRuleSets) {
                sysRuleSet.setId(letter + sysRuleSet.getId().substring(letter.length()));
                sysRuleSet.setOrgId(organizationDTO.getGoalOrgId());
            }
            sysRuleSetService.saveBatch(sysRuleSets);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //todo
        }
        return Result.succ("操作成功");
    }

}
